package com.atguigu.gmall.filter;

import cn.hutool.core.util.IdUtil;
import com.atguigu.gmall.component.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author Jerry.Su
 * @Date 2022/2/21 9:41
 * @description springmvc filter 用于生成traceId,绑定到threadlocal对象
 */
public class TraceIdContextFilter extends OncePerRequestFilter {

    public static final Logger log = LoggerFactory.getLogger(TraceIdContextFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        RequestContext.clear();
        generateTraceId();
        filterChain.doFilter(request, response);
    }

    protected void generateTraceId() {
        String traceId = IdUtil.fastSimpleUUID();
        log.info("generate traceId {}", traceId);
        RequestContext.setTraceId(traceId);
    }
}
